<script setup lang="ts">
import { FitAddon } from '@xterm/addon-fit';
import { Terminal } from '@xterm/xterm';
import { onMounted, onUnmounted, Ref, ref, watch } from 'vue';

const content = defineModel() as Ref<string>;
const terminal = ref({} as Terminal);
const terminalContainer = ref<HTMLElement | null>(null);
const fitAddon = ref({} as FitAddon);

onMounted(async () => {
    initTerm();
})

watch(() => content.value, () => {
    console.log(content.value);
    terminal.value.clear();
    terminal.value.write(content.value)
})

onUnmounted(() => {
    window.removeEventListener('resize', () => {
        fitAddon.value.fit();
    });
})

const initTerm = () => {
    terminal.value = new Terminal({
        theme: {
            foreground: '#D4D4D4', // 文本颜色
            background: 'black', // 背景颜色
            cursor: '#569CD6', // 光标颜色
        }
    })
    fitAddon.value = new FitAddon();
    terminal.value.loadAddon(fitAddon.value);
    if (terminalContainer.value) {
        terminal.value.open(terminalContainer.value);
    }
    fitAddon.value.fit();
    // 监听窗口大小变化，调整终端大小
    window.addEventListener('resize', () => {
        fitAddon.value.fit();
    });
}
</script>

<template>
    <div ref="terminalContainer" class="terminal-container"></div>
</template>

<style lang="scss" scoped>
.terminal-container {
    display: flex;
    width: 100%;
}
</style>

<style>
/* 隐藏滚动条 */
.xterm-viewport::-webkit-scrollbar {
    display: none;
    /* 针对 WebKit 浏览器（如 Chrome、Safari） */
}

.xterm-viewport {
    scrollbar-width: none;
    /* 针对 Firefox */
    -ms-overflow-style: none;
    /* 针对 IE/Edge */
}
</style>